package com.servlet;

import com.dao.imp.FindCollectStatus;
import com.dao.imp.FindGoodsDaoImp;
import com.entity.Good;
import com.entity.GoodStatus;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author Mathison
 * @Title: ${NAME}
 * @Package: ${PACKAGE_NAME}
 * @Description: TODO
 * @date 2021/11/26 13:58
 **/

@WebServlet(name = "GetUserCollectionServlet", value = "/GetUserCollectionServlet")
public class GetUserCollectionServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/html;charset=utf-8");
        HttpSession session = request.getSession();
        int user_id = Integer.parseInt(session.getAttribute("userId").toString());
        List<Good> goodList = new ArrayList<>();
        FindGoodsDaoImp findGoodsDaoImp = new FindGoodsDaoImp();

        String sql = "SELECT * FROM user_collect WHERE user_id="+user_id;
        List<GoodStatus> allCollection = FindCollectStatus.findAllGollection(sql);
        for (GoodStatus goodStatus:
             allCollection) {
            String getGoodSql = "SELECT * FROM goods WHERE good_id="+goodStatus.getGood_id();
//            System.out.println(getGoodSql);
            goodList.add(findGoodsDaoImp.getGood(getGoodSql));
        }

        JSONArray jsonArray = new JSONArray();

        for (Good good:
             goodList) {
//            System.out.println(good.getGood_id());
            String mainUrl = good.getGood_url().split(",")[0];
            int good_id = good.getGood_id();
            String good_name = good.getGood_name();
            double good_price = good.getGood_price();

            String jsonString = "{id:"+good_id+",name:\""+good_name+"\",price:"+good_price+",mainImage:\""+mainUrl+"\"}";
            JSONObject json = JSONObject.fromObject(jsonString);
            jsonArray.add(json);
        }

        response.getWriter().print(jsonArray);
    }
}
